package controller.login;/*
 * Created by JFormDesigner on Fri Dec 16 20:10:05 CST 2022
 */

import controller.menu.AdminUserMenu;
import controller.menu.NormalUserMenu;
import model.AdminUser;
import model.NormalUser;
import model.User;
import controller.reg.Register;
import util.AdminDao;
import util.NormalUserDao;
import view.login.LoginFrameView;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/**
 * @author unknown
 */
public class Login implements ActionListener {
    LoginFrameView loginFrame = new LoginFrameView();
    public void login() {
        //添加监视器
        loginFrame.getEnter().addActionListener(this);
        loginFrame.getReg().addActionListener(this);
        //设置可见
        loginFrame.setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        boolean isAdmin = loginFrame.getRadioButton1().isSelected();
        if(e.getSource()==loginFrame.getEnter()) {
            if(isAdmin) {
                //从管理员中查询
                AdminDao adminDao = new AdminDao();
                checkLog(adminDao.selectByName(loginFrame.getUsername().getText()),loginFrame.getPassword().getText(),isAdmin);
            } else {
                //从用户中查询
                NormalUserDao normalUserDao = new NormalUserDao();
                NormalUser user = normalUserDao.getByName(loginFrame.getUsername().getText());
                checkLog(user,loginFrame.getPassword().getText(),isAdmin);
            }
        } else if(e.getSource()==loginFrame.getReg()) {
            //跳转到注册页面
            loginFrame.setVisible(false);
            Register register = new Register();
            register.reg();
        }
    }
    //检查用户登录是否成功
    public void checkLog(User user, String password,boolean isAdmin) {
        JPanel center = loginFrame.getCenter();
        if(user ==null) {
            JOptionPane.showMessageDialog(center,"不存在该用户");
        }
        if(user.getPassword().equals(password)) {
            JOptionPane.showMessageDialog(center,"登录成功");
            if(isAdmin) {
                AdminUserMenu adminUserMenu = new AdminUserMenu((AdminUser) user);
                adminUserMenu.init();
                loginFrame.setVisible(false);
            } else {
                NormalUserMenu normalUserMenu = new NormalUserMenu((NormalUser) user);
                normalUserMenu.init();
                loginFrame.setVisible(false);
            }
        } else {
            JOptionPane.showMessageDialog(center,"密码错误");
        }
    }
}
